<template>
    <div :class="['pe-option', disabled || groupDisabled ? 'pe-option-disabled' : '', getSelect() ? 'pe-option-selected' : '']"
        @click.stop="onClick">
        <div>
            <slot>
                <span>{{ label }}</span>
            </slot>
        </div>
        <Check v-if="modelValue instanceof Array && modelValue.includes(props.value)" />
    </div>
</template>

<script setup lang="ts">
import { inject, ref } from "vue"
import Check from "../../icons/check.vue";

/**
 * @param value 选中值
 * @param label 显示值
 * @param disabled 是否禁用
 */
interface Props {
    value: string | number
    label?: string | number
    disabled?: boolean
}

const props = withDefaults(defineProps<Props>(), {
    disabled: false
})

type ValueType = string | number | Array<string | number>

// 绑定值
const modelValue = inject("pe-select-value", ref<ValueType>(""))
// 是否多选
const multiple = inject("pe-select-multiple", ref<boolean>(false))
// 改变值时触发函数
const onChange = inject("pe-select-change", Function, true)
// 展示的数据
const showValue = inject("pe-select-showValue", ref<ValueType>(""))
// 分组禁用
const groupDisabled = inject("pe-option-group-disabled", ref<boolean>(false))

const getSelect = () => {
    return modelValue.value === props.value || (modelValue.value instanceof Array && modelValue.value.includes(props.value))
}

const onClick = () => {
    if(props.disabled || groupDisabled.value) return
    if (!multiple) {
        if (modelValue.value !== props.value) {
            modelValue.value = props.value
            if (props.label) {
                showValue.value = props.label
            } else {
                showValue.value = props.value
            }
            onChange(props.value)
        }
    } else {
        let arr: Array<string | number> = []
        let labelArr: Array<string | number> = []
        if (modelValue.value instanceof Array) {
            arr = JSON.parse(JSON.stringify(modelValue.value))
            labelArr = JSON.parse(JSON.stringify(showValue.value))
        }
        if (arr.includes(props.value)) {
            let index = 0
            arr = arr.filter((item, idx) => {
                if (item === props.value) {
                    index = idx
                }
                return item !== props.value
            })
            labelArr = labelArr.filter((_item, idx) => idx !== index)
        } else {
            arr.push(props.value)
            labelArr.push(props.label ? props.label : props.value)
        }
        modelValue.value = arr
        showValue.value = labelArr
        onChange(arr)
    }
}
</script>

<script lang="ts">
export default {
    name: "pe-option"
}
</script>